<template>
  <el-drawer
    title="翻译任务管理"
    :visible.sync="drawerVisible"
    direction="rtl"
    size="600px"
    :before-close="handleClose"
  >
    <div class="translate-task-manager">
      <!-- 创建新任务区域 -->
      <div class="create-task-section">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;">
              <i class="el-icon-plus" /> 创建新翻译任务
            </span>
          </div>
          <div class="create-form">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-select
                  v-model="selectedLanguageId"
                  placeholder="选择目标语言"
                  size="small"
                  clearable
                  style="width: 100%"
                  :loading="languagesLoading"
                >
                  <el-option
                    v-for="language in availableLanguages"
                    :key="language.id"
                    :label="language.name"
                    :value="language.id"
                  >
                    <span :style="{ color: language.color }">{{ language.name }}</span>
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="12">
                <el-button
                  type="primary"
                  size="small"
                  :loading="creating"
                  :disabled="!selectedLanguageId"
                  @click="handleCreateTask"
                >
                  创建翻译任务
                </el-button>
              </el-col>
            </el-row>
            <el-row v-if="completedTasks.length > 0" :gutter="20" style="margin-top: 10px;">
              <el-col :span="24">
                <el-button
                  type="warning"
                  size="small"
                  :loading="batchRetranslating"
                  icon="el-icon-refresh"
                  @click="handleBatchRetranslate"
                >
                  批量重新翻译 ({{ completedTasks.length }} 个已完成任务)
                </el-button>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </div>

      <!-- 任务列表区域 -->
      <div class="task-list-section">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;">
              <i class="el-icon-list" /> 翻译任务列表
            </span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="fetchTranslateTasks"
            >
              刷新
            </el-button>
          </div>

          <div v-loading="tasksLoading" class="task-list">
            <div v-if="translateTasks.length === 0" class="empty-state">
              <div class="empty-content">
                <i class="el-icon-document empty-icon" />
                <p class="empty-text">暂无翻译任务</p>
              </div>
            </div>

            <el-timeline v-else>
              <el-timeline-item
                v-for="task in translateTasks"
                :key="task.id"
                :timestamp="task.create_at"
                placement="top"
                :type="getTimelineType(task.status)"
                :icon="getTimelineIcon(task.status)"
              >
                <el-card class="task-card">
                  <div class="task-header">
                    <div class="task-title">
                      <span class="language-name" :style="{ color: task.target_language__color }">
                        {{ task.target_language__name }}
                      </span>
                      <el-tag :type="getStatusType(task.status)" size="mini">
                        {{ getStatusText(task.status) }}
                      </el-tag>
                    </div>
                    <div class="task-actions">
                      <el-button
                        v-if="task.status === 'completed' && task.translated_post__id"
                        type="text"
                        size="mini"
                        @click="handleViewTranslation(task.translated_post__id)"
                      >
                        查看译文
                      </el-button>
                      <el-button
                        v-if="task.status === 'completed'"
                        type="text"
                        size="mini"
                        style="color: #67c23a"
                        :loading="task.retranslating"
                        @click="handleRetranslateTask(task)"
                      >
                        重新翻译
                      </el-button>
                      <el-button
                        v-if="task.status === 'failed' || task.status === 'pending'"
                        type="text"
                        size="mini"
                        style="color: #f56c6c"
                        @click="handleDeleteTask(task)"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>

                  <div v-if="task.translated_post__title" class="task-content">
                    <p><strong>译文标题：</strong>{{ task.translated_post__title }}</p>
                  </div>

                  <div v-if="task.error_message" class="task-error">
                    <el-alert
                      :title="task.error_message"
                      type="error"
                      :closable="false"
                      show-icon
                    />
                  </div>

                  <div class="task-meta">
                    <span class="creator">创建者：{{ task.creator__username }}</span>
                    <span v-if="task.completed_at" class="completed-time">
                      完成时间：{{ task.completed_at }}
                    </span>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import {
  GetTranslateTaskList,
  CreateTranslateTask,
  DeleteTranslateTask,
  PostRetranslate
} from '@/api/cms/post'
import { Get as GetLanguages } from '@/api/cms/language'

export default {
  name: 'TranslateTaskManager',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    postId: {
      type: [String, Number],
      required: true
    },
    postTitle: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      drawerVisible: false,
      selectedLanguageId: null,
      creating: false,
      tasksLoading: false,
      languagesLoading: false,
      batchRetranslating: false,

      translateTasks: [],
      languages: [],

      // 轮询相关
      pollingTimer: null,
      pollingInterval: 5000 // 5秒轮询一次
    }
  },
  computed: {
    // 获取可用的语言列表（排除已经存在翻译任务的语言）
    availableLanguages() {
      const existingLanguageIds = this.translateTasks
        .filter(task => task.status !== 'failed') // 失败的任务可以重新创建
        .map(task => task.target_language_id)

      return this.languages.filter(lang => !existingLanguageIds.includes(lang.id))
    },
    // 获取已完成的翻译任务
    completedTasks() {
      return this.translateTasks.filter(task => task.status === 'completed')
    }
  },
  watch: {
    visible(newVal) {
      this.drawerVisible = newVal
      if (newVal) {
        this.init()
      } else {
        this.stopPolling()
      }
    },
    drawerVisible(newVal) {
      this.$emit('update:visible', newVal)
      if (!newVal) {
        this.stopPolling()
      }
    }
  },
  beforeDestroy() {
    this.stopPolling()
  },
  methods: {
    // 初始化
    init() {
      this.fetchLanguages()
      this.fetchTranslateTasks()
      this.startPolling()
    },

    // 获取语言列表
    async fetchLanguages() {
      this.languagesLoading = true
      try {
        const response = await GetLanguages()
        this.languages = response.data.data || []
      } catch (error) {
        console.error('获取语言列表失败:', error)
        this.$message.error('获取语言列表失败')
      } finally {
        this.languagesLoading = false
      }
    },

    // 获取翻译任务列表
    async fetchTranslateTasks() {
      if (!this.postId) return

      this.tasksLoading = true
      try {
        const params = new URLSearchParams({
          source_post_id: this.postId,
          pagesize: 50
        }).toString()

        const response = await GetTranslateTaskList(params)
        this.translateTasks = response.data.data || []
      } catch (error) {
        console.error('获取翻译任务列表失败:', error)
        this.$message.error('获取翻译任务列表失败')
      } finally {
        this.tasksLoading = false
      }
    },

    // 创建翻译任务
    async handleCreateTask() {
      if (!this.selectedLanguageId) {
        this.$message.warning('请选择目标语言')
        return
      }

      this.creating = true
      try {
        const data = {
          source_post_id: this.postId,
          target_language_id: this.selectedLanguageId
        }

        await CreateTranslateTask(JSON.stringify(data))
        this.$message.success('翻译任务创建成功，正在后台处理...')

        // 重置选择
        this.selectedLanguageId = null

        // 刷新任务列表
        this.fetchTranslateTasks()
      } catch (error) {
        console.error('创建翻译任务失败:', error)
        this.$message.error(error.response?.data?.msg || '创建翻译任务失败')
      } finally {
        this.creating = false
      }
    },

    // 删除翻译任务
    async handleDeleteTask(task) {
      try {
        await this.$confirm(`确定要删除翻译到 ${task.target_language__name} 的任务吗？`, '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await DeleteTranslateTask(task.id)
        this.$message.success('翻译任务已删除')

        // 刷新任务列表
        this.fetchTranslateTasks()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除翻译任务失败:', error)
          this.$message.error(error.response?.data?.msg || '删除翻译任务失败')
        }
      }
    },

    // 重新翻译任务
    async handleRetranslateTask(task) {
      try {
        // 先提示用户保存内容
        await this.$confirm(
          '重新翻译将使用当前页面的最新内容。建议您先保存当前的修改内容，然后再进行重新翻译。<br/><br/>是否继续重新翻译？',
          '提示：建议先保存内容',
          {
            confirmButtonText: '继续重新翻译',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
            distinguishCancelAndClose: true,
            showCancelButton: true,
            showClose: true
          }
        )

        // 显示重新翻译确认对话框
        await this.$confirm(
          `确定要重新翻译到 ${task.target_language__name} 吗？这将会：<br/>
          - 使用当前最新的文章内容重新翻译<br/>
          - 覆盖现有的翻译内容<br/>
          - 任务状态将变为"翻译中"`,
          '确认重新翻译',
          {
            confirmButtonText: '强制重新翻译',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
            distinguishCancelAndClose: true,
            showCancelButton: true,
            showClose: true
          }
        )

        // 设置任务的重新翻译状态
        this.$set(task, 'retranslating', true)

        const data = {
          post_id: this.postId,
          language_ids: [task.target_language_id],
          force_retranslate: true
        }

        const response = await PostRetranslate(JSON.stringify(data))

        if (response.data.success) {
          const result = response.data.data
          this.$message.success(response.data.msg || '重新翻译任务已创建')

          // 显示重新翻译的详细信息
          if (result.retranslated_tasks && result.retranslated_tasks.length > 0) {
            const retranslatedTask = result.retranslated_tasks[0]
            this.$notify({
              title: '重新翻译已开始',
              message: `${retranslatedTask.target_language} - ${retranslatedTask.reason}`,
              type: 'success',
              duration: 3000
            })
          }

          // 刷新任务列表
          this.fetchTranslateTasks()

          // 通知父级组件刷新 post 数据
          this.$emit('refresh-post')
        }
      } catch (error) {
        if (error !== 'cancel' && error !== 'close') {
          console.error('重新翻译失败:', error)
          this.$message.error(error.response?.data?.msg || '重新翻译任务创建失败')
        }
      } finally {
        // 清除重新翻译状态
        this.$set(task, 'retranslating', false)
      }
    },

    // 批量重新翻译
    async handleBatchRetranslate() {
      if (this.completedTasks.length === 0) {
        this.$message.warning('没有已完成的翻译任务')
        return
      }

      try {
        // 先提示用户保存内容
        await this.$confirm(
          '批量重新翻译将使用当前页面的最新内容。建议您先保存当前的修改内容，然后再进行批量重新翻译。<br/><br/>是否继续批量重新翻译？',
          '提示：建议先保存内容',
          {
            confirmButtonText: '继续批量重新翻译',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          }
        )

        const languageNames = this.completedTasks.map(task => task.target_language__name).join('、')
        await this.$confirm(
          `确定要重新翻译所有 ${this.completedTasks.length} 个已完成的翻译任务吗？<br/>
          包含语言：${languageNames}<br/><br/>
          这将会：<br/>
          - 使用当前最新的文章内容重新翻译<br/>
          - 覆盖现有的翻译内容<br/>
          - 所有任务状态将变为"翻译中"`,
          '确认批量重新翻译',
          {
            confirmButtonText: '强制重新翻译',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          }
        )

        this.batchRetranslating = true

        const languageIds = this.completedTasks.map(task => task.target_language_id)
        const data = {
          post_id: this.postId,
          language_ids: languageIds,
          force_retranslate: true
        }

        const response = await PostRetranslate(JSON.stringify(data))

        if (response.data.success) {
          const result = response.data.data
          this.$message.success(response.data.msg || '批量重新翻译任务已创建')

          // 显示详细结果
          if (result.retranslated_tasks && result.retranslated_tasks.length > 0) {
            const taskList = result.retranslated_tasks.map(task =>
              `${task.target_language} (${task.reason})`
            ).join('<br/>')

            this.$notify({
              title: `批量重新翻译已开始 (${result.total_retranslated}个)`,
              message: taskList,
              type: 'success',
              duration: 5000,
              dangerouslyUseHTMLString: true
            })
          }

          if (result.skipped_tasks && result.skipped_tasks.length > 0) {
            const skippedList = result.skipped_tasks.map(task =>
              `${task.target_language} (${task.reason})`
            ).join('<br/>')

            this.$notify({
              title: `跳过的任务 (${result.total_skipped}个)`,
              message: skippedList,
              type: 'info',
              duration: 5000,
              dangerouslyUseHTMLString: true
            })
          }

          // 刷新任务列表
          this.fetchTranslateTasks()

          // 通知父级组件刷新 post 数据
          this.$emit('refresh-post')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量重新翻译失败:', error)
          this.$message.error(error.response?.data?.msg || '批量重新翻译任务创建失败')
        }
      } finally {
        this.batchRetranslating = false
      }
    },

    // 查看翻译文章
    handleViewTranslation(translatedPostId) {
      const routeData = this.$router.resolve({
        name: 'EditPost',
        params: { post_id: translatedPostId }
      })
      window.open(routeData.href, '_blank')
    },

    // 获取状态对应的标签类型
    getStatusType(status) {
      const statusMap = {
        pending: 'info',
        processing: 'warning',
        completed: 'success',
        failed: 'danger'
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        pending: '待处理',
        processing: '翻译中',
        completed: '已完成',
        failed: '失败'
      }
      return statusMap[status] || '未知'
    },

    // 获取时间轴类型
    getTimelineType(status) {
      const typeMap = {
        pending: 'info',
        processing: 'warning',
        completed: 'success',
        failed: 'danger'
      }
      return typeMap[status] || 'info'
    },

    // 获取时间轴图标
    getTimelineIcon(status) {
      const iconMap = {
        pending: 'el-icon-time',
        processing: 'el-icon-loading',
        completed: 'el-icon-check',
        failed: 'el-icon-close'
      }
      return iconMap[status] || 'el-icon-time'
    },

    // 开始轮询
    startPolling() {
      // 清除之前的定时器
      this.stopPolling()

      // 设置新的定时器
      this.pollingTimer = setInterval(() => {
        // 只有当存在处理中的任务时才轮询
        const hasProcessingTasks = this.translateTasks.some(
          task => task.status === 'pending' || task.status === 'processing'
        )

        if (hasProcessingTasks) {
          this.fetchTranslateTasks()
        }
      }, this.pollingInterval)
    },

    // 停止轮询
    stopPolling() {
      if (this.pollingTimer) {
        clearInterval(this.pollingTimer)
        this.pollingTimer = null
      }
    },

    // 关闭抽屉
    handleClose() {
      this.drawerVisible = false
    }
  }
}
</script>

<style scoped>
.translate-task-manager {
  padding: 20px;
}

.create-task-section {
  margin-bottom: 20px;
}

.create-form {
  padding: 10px 0;
}

.task-list-section {
  flex: 1;
}

.task-list {
  min-height: 200px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  font-size: 48px;
  color: #d3dce6;
  margin-bottom: 16px;
}

.empty-text {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.task-card {
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.task-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.language-name {
  font-weight: bold;
  font-size: 16px;
}

.task-actions {
  display: flex;
  gap: 5px;
}

.task-content {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.task-error {
  margin-bottom: 10px;
}

.task-meta {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #909399;
}

.creator, .completed-time {
  display: flex;
  align-items: center;
}

/* Element UI 时间轴样式调整 */
.el-timeline {
  padding-left: 0;
}

.el-timeline-item {
  padding-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .task-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .task-actions {
    align-self: flex-end;
  }

  .task-meta {
    flex-direction: column;
    gap: 5px;
  }
}
</style>
